package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.ArticleForEsConstants;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.WmNewsMessageConstants;
import com.heima.common.constants.wemedia.WemediaContans;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.NewsAuthDto;
import com.heima.model.media.dtos.WmNewsDto;
import com.heima.model.media.dtos.WmNewsPageReqDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmNews;
import com.heima.model.media.pojos.WmNewsMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.media.vo.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Log4j2
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${fdfs.url}")
    private String url;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    //admin端调用查询人工审核文章列表
    public ResponseResult findListAndPage(NewsAuthDto dto) {
        if (dto==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        dto.checkParam();
        String title = dto.getTitle();
        if (StringUtils.isNotBlank(title))
            dto.setTitle("%"+title+"%");
        Integer page = dto.getPage();
        Integer size = dto.getSize();
        dto.setPage((page-1)*size);
        List<WmNewsVo> list = baseMapper.findListAndPage(dto);
        long count = baseMapper.findListCount(dto);
        PageResponseResult responseResult = new PageResponseResult(page, size, (int) count);
        responseResult.setData(list);
        return responseResult;
    }

    @Override
    //admin端调用查询人工审核文章详情
    public WmNewsVo findWmNewsVo(Integer id) {
        return baseMapper.findWmNewsVo(id);
    }

    //定时任务调用  查询需要发布的文章id  (status==4/8 and 发布时间小于等于now)
    @Override
    public List<Integer> findRelease() {
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.<WmNews>lambdaQuery()
                .le(WmNews::getPublishTime,new Date()).and(wrapper->
            wrapper.eq(WmNews::getStatus,4).or().eq(WmNews::getStatus,8)
        );
        log.info("查询待发布文章的id信息");
        List<WmNews> list = list(queryWrapper);
        return list.stream().map(WmNews::getId).collect(Collectors.toList());
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto==null||dto.getId()==null||(dto.getEnable()!=0&&dto.getEnable()!=1))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, dto.getId()).eq(WmNews::getUserId, WmThreadLocalUtils.getUser().getId()));
        if (wmNews==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        if (!WmNews.Status.PUBLISHED.getCode().equals(wmNews.getStatus()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章未发布，不能上架");
        boolean b = update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable, dto.getEnable()).eq(WmNews::getId, dto.getId()));
        if (b){
            Map<String,Object> map = new HashMap<>();
            map.put("articleId",wmNews.getArticleId());
            map.put("enable",dto.getEnable());
            //发送消息 修改article_config的上下架状态
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            if (dto.getEnable()==1) {
                kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD, String.valueOf(wmNews.getArticleId()));
            } else{
                kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_DELETE,String.valueOf(wmNews.getArticleId()));
            }
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult delNews(Integer id) {
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"缺少文章id");
        }
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id).eq(WmNews::getUserId, WmThreadLocalUtils.getUser().getId()));
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable()==1){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));

        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if (id==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
        List<Map> collect = maps.stream().map(
                m -> {
                    if ("image".equals(m.get("type"))) {
                        String imageUrl = (String) m.get("value");
                        m.put("value", url + imageUrl);
                    }
                    return m;
                }
        ).collect(Collectors.toList());
        wmNews.setContent(JSON.toJSONString(collect));
        // 3. 返回结果
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(url);
        return responseResult;
    }

    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        if (dto==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        Page page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getUserId,user.getId());
        if (dto.getStatus()!=null)
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        if (dto.getChannelId()!=null)
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        if (StringUtils.isNotBlank(dto.getKeyword()))
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        if (dto.getBeginPubDate()!=null)
            queryWrapper.ge(WmNews::getPublishTime,dto.getBeginPubDate());
        if (dto.getEndPubDate()!=null)
            queryWrapper.le(WmNews::getPublishTime,dto.getEndPubDate());
        queryWrapper.orderByDesc(WmNews::getPublishTime);
        IPage<WmNews> ipage = page(page, queryWrapper);

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) ipage.getTotal());
        pageResponseResult.setData(ipage.getRecords());
        pageResponseResult.setHost(url);
        return pageResponseResult;
    }

    //自媒体端文章发表或存草稿
    @Override
    public ResponseResult saveNews(WmNewsDto dto) {
        if(dto==null||StringUtils.isBlank(dto.getContent()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (checkStatus(dto.getStatus()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        wmNews.setContent(dto.getContent().replaceAll(url,""));
        List<String> coverImages = dto.getImages();
        if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType()))
            wmNews.setType(null);
        if (coverImages!=null&&!coverImages.isEmpty()){
            coverImages = coverImages.stream().map(item -> item.replace(url, "").trim()).collect(Collectors.toList());
            String imageStr = StringUtils.join(coverImages, ",");
            wmNews.setImages(imageStr);
        }
        wmNews.setUserId(user.getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        saveOrUpdateNews(wmNews);
        List<String> contentImages = cutImages(dto.getContent());
        //保存news中与content中图片相关的素材的中间表信息
        if (!WmNews.Status.NORMAL.getCode().equals(dto.getStatus())&&!contentImages.isEmpty())
            saveRelativeInfo(contentImages,wmNews.getId(),WemediaContans.WM_CONTENT_REFERENCE);
        //如果封面为自动，修改news的type信息，提取content图片到作为封面
        if(!contentImages.isEmpty()&&WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType()))
            coverImages=autoSetCoverImages(wmNews,contentImages);
        //保存news中与封面图片相关的素材中间表信息
        if (!WmNews.Status.NORMAL.getCode().equals(dto.getStatus())&&!coverImages.isEmpty())
            saveRelativeInfo(coverImages,wmNews.getId(),WemediaContans.WM_COVER_REFERENCE);
        //如果不是草稿，发送kafka信息，让admin端自动审核news
        if(wmNews.getStatus()==1){
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(wmNews.getId()));
        }

        return ResponseResult.okResult();
    }

    private List<String> autoSetCoverImages(WmNews wmNews, List<String> contentImages) {
        int size = contentImages.size();
        if (size >= 3) {
            contentImages = contentImages.stream().limit(3).collect(Collectors.toList());
            wmNews.setType(WemediaContans.WM_NEWS_MANY_IMAGE);
        }else if (size > 0){
            contentImages=contentImages.stream().limit(1).collect(Collectors.toList());
            wmNews.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
        }else{
            wmNews.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
        }
        updateById(wmNews);
        return contentImages;
    }

    private void saveRelativeInfo(List<String> images, Integer id, Short type) {

        HashSet<String> set = new HashSet<>(images);

        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery().select(WmMaterial::getId).eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId());
        if (!set.isEmpty())
            queryWrapper.in(WmMaterial::getUrl, set);
        List<Object> list =wmMaterialMapper.selectObjs(queryWrapper);
        if (list==null||list.isEmpty())
            throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关联素材不存在"));
        if (set.size()!=list.size())
            throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关联素材不存在"));
        List<Long> materialIds = list.stream().map(item -> (Long)item).collect(Collectors.toList());
        wmNewsMaterialMapper.batchSaveRelations(materialIds,id,type);
    }

    private List<String> cutImages(String content) {
        ArrayList<String> list = new ArrayList<>();
        List<Map> listMap = JSONArray.parseArray(content, Map.class);
        for (Map map : listMap) {
            String type = (String)map.get("type");
            if (WemediaContans.WM_NEWS_TYPE_IMAGE.equals(type)) {
                String value = (String) map.get("value");
                list.add(value.replace(url,"").trim());
            }
        }
        return list;
    }

    private void saveOrUpdateNews(WmNews wmNews) {
        if (wmNews.getId()==null){
            save(wmNews);
        }else {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }

    private boolean checkStatus(Short status) {
        return status == null || (!status.equals(WmNews.Status.SUBMIT.getCode()) && !status.equals(WmNews.Status.NORMAL.getCode()));
    }
}
